package com.taotao.config;

import com.google.common.util.concurrent.RateLimiter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author 余胜军
 * @ClassName RateLimiter
 * @qq 644064779
 * @addres www.mayikt.com
 * 微信:yushengjun644
 */
@Component
public class RateLimiterFilter implements GlobalFilter {
    /**
     * 限流 qps 1  每s 只会向 令牌桶中 投递一个token
     */
    private RateLimiter rateLimiter = RateLimiter.create(1);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        boolean result = rateLimiter.tryAcquire();
        if (!result) {
            ServerHttpResponse response = exchange.getResponse();
            String msg = "Interface access frequency is too high, please try again later";
            DataBuffer buffer = response.bufferFactory().wrap(msg.getBytes());
            return response.writeWith(Mono.just(buffer));
        }
        // 放行请求
        return chain.filter(exchange.mutate().build());
    }
}
